package sf01.studentmngmsystem.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sf01.studentmngmsystem.entity.Teacher;
import sf01.studentmngmsystem.service.TeacherService;

import jakarta.servlet.http.HttpSession;

@Controller
@RequestMapping("/teacher")
public class TeacherLoginController {
    
    @Autowired
    private TeacherService teacherService;
    
    /**
     * 显示教师登录页面
     */
    @GetMapping("/login")
    public String showLoginPage() {
        return "teacher-login";
    }
    
    /**
     * 处理教师登录
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                       @RequestParam String password,
                       HttpSession session,
                       Model model) {
        
        Teacher teacher = teacherService.login(username, password);
        
        if (teacher != null) {
            // 登录成功，将教师信息存入session
            session.setAttribute("teacher", teacher);
            session.setAttribute("teacherName", teacher.getName());
            
            // 重定向到学生管理页面
            return "redirect:/students";
        } else {
            // 登录失败
            model.addAttribute("error", "用户名或密码错误");
            return "teacher-login";
        }
    }
    
    /**
     * 教师退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("teacher");
        session.removeAttribute("teacherName");
        return "redirect:/teacher/login";
    }
}